<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Contract as ContractModel;
use addons\qingdong\model\ContractFile;
use addons\qingdong\model\ContractOther;
use addons\qingdong\model\ExamineRecord;
use addons\qingdong\model\FormField;
use addons\qingdong\model\Ratio;
use addons\qingdong\model\Receivables;
use addons\qingdong\model\Message;
use addons\qingdong\model\Staff;
use think\Db;
use think\Exception;

/**
 * 合同接口
 */
class Contract extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];


    //创建合同
    public function addContract()
    {
        $params = $this->request->post();

        // 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params);
        if ($result !== true) {
            $this->error($result);
        }
        if (isset($params['num'])) {
            if (empty($params['num'])) {
                $params['num'] = ContractModel::getNum();
            }
            $contract = ContractModel::where(['num' => $params['num']])->find();
            if ($contract) {
                $this->error('合同编号已存在');
            }
        } else {
            $params['num'] = ContractModel::getNum();
        }
        Db::startTrans();
        try {

            $result = ContractModel::createContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加合同成功');
        }
    }


    //获取select合同列表
    public function getSelectList()
    {
        $customer_id = input('customer_id');
        $name = input('name','');
        $where = [];
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($name) {
            $where['name'] = ["like","%$name%"];
        }
        $records = ContractModel::where($where)->where(['check_status'=>2])->with(['ownerStaff'])->field('id,name,num,order_date,money')->order('id desc')->select();
        $this->success('请求成功', $records);
    }


    //获取合同列表
    public function getList()
    {
        $limit = input("limit/d", 10);
        $customer_id = input('customer_id');
        $contacts_id = input('contacts_id');
        $status = input('status',0);

        $params = $this->request->post();

        $whereT =[];
        $where= FormField::updateWhereField(FormField::CONTRACT_TYPE,$params);
        if (isset($params['createtime']) && $params['createtime']) {//跟进状态
            $createtime = $params['createtime'];
            $createtime = explode(',', $createtime);
            $where['order_date'] = ['between', [date('Y-m-d 00:00:00',strtotime($createtime[0])), date('Y-m-d 23:59:59',strtotime($createtime[1]) + 86400 - 1)]];
        }
        if (isset($params['staff_id']) && $params['staff_id']) {//下级员工筛选
            $where['owner_staff_id'] = $params['staff_id'];
        } else {
            $where['owner_staff_id'] = ['in', Staff::getMyStaffIds()];
            if (isset($params['type']) && $params['type']) {//客户分类
                if ($params['type'] == 1) {//我的客户
                    $where['owner_staff_id'] = $this->auth->id;
                } elseif ($params['type'] == 2) {//下属负责的客户
                    $where['owner_staff_id'] = ['in', Staff::getLowerStaffId()];
                }
            }
        }

        if ($status) {
            if($status == 1){//待审核
                $where['check_status']=['in',[0,1]];
            }elseif($status == 2){//待回款
                $where['check_status']=2;
                $where['contract_status']=0;
            }elseif($status == 3){//已回款
                $where['check_status']=2;
                $where['contract_status']=1;
            }
        }
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($contacts_id) {
            $where['contacts_id'] = $contacts_id;
        }
        $records = ContractModel::where($where)->with([
            'customer',
            'contacts',
            'ownerStaff',
            'orderStaff',
            'receivables'
        ])->order('id desc')->paginate($limit)->toArray();
        $data = $records['data'];

        foreach ($data as $k => $v) {
            if (empty($v['receivables'])) {
                $v['receivables'] = [
                    'repayment_money' => 0,
                    'be_money' => $v['money'],
                    'ratio' => 0
                ];
            } else {
                $be_money = $v['money'] - $v['receivables']['repayment_money'];
                $be_money =   ($be_money > 0) ? $be_money : 0;
                $ratio_m = 0;
                if($v['money'] >0){
                    $ratio_m = round($v['receivables']['repayment_money'] / $v['money'] * 100, 2);
                }
                $v['receivables'] = [
                    'repayment_money' => $v['receivables']['repayment_money'],
                    'be_money' =>$be_money,
                    'ratio' => $ratio_m
                ];
            }
            $data[$k] = $v;
        }

        $whereT['owner_staff_id']=$where['owner_staff_id'];
        $noMoney = ContractModel::where($whereT)->where(array('check_status'=>2))->sum('money');
        $moneyinfo['repayment_money'] = Receivables::where($whereT)->where(array('check_status'=>2))->sum('money'); //已回款
        $moneyinfo['be_money'] = sprintf("%.2f",$noMoney)-sprintf("%.2f",$moneyinfo['repayment_money']);//未回款
        $moneyinfo['allmoney'] = $noMoney;//合同总金额
        $this->success('请求成功', ['moneyinfo' => $moneyinfo, 'total' => $records['total'], 'per_page' => $records['per_page'], 'current_page' => $records['current_page'], 'last_page' => $records['last_page'], 'data' => $data]);
    }


    //获取客户相关合同列表
    public function getCustomerContacts()
    {
        $customer_id = input('customer_id');
        $contacts_id = input('contacts_id');
        $where = [];
        if ($customer_id) {
            $where['customer_id'] = $customer_id;
        }
        if ($contacts_id) {
            $where['contacts_id'] = $contacts_id;
        }
        $records = ContractModel::where($where)->with(['receivables'])->field('id,name,money,num,check_status,order_date')->order('id desc')->select();
        $records = collection($records)->toArray();
        foreach ($records as $k => $v) {
            if (empty($v['receivables'])) {
                $v['receivables'] = [
                    'repayment_money' => 0,
                    'be_money' => $v['money'],
                    'ratio' => 0
                ];
            } else {
                $be_money = $v['money'] - $v['receivables']['repayment_money'];
                $v['receivables'] = [
                    'repayment_money' => $v['receivables']['repayment_money'],
                    'be_money' => ($be_money > 0) ? $be_money : 0,
                    'ratio' => round($v['receivables']['repayment_money'] / $v['money'] * 100, 2)
                ];
            }
            $records[$k] = $v;
        }
        $this->success('请求成功', $records);
    }


    //获取合同详情
    public function getDetail()
    {
        $id = input('id');
        $contract = ContractModel::where(['id' => $id])->with([
            'customer',
            'contacts',
            'ownerStaff',
            'orderStaff',
            'product',
            'receivables',
            'business'
        ])->find();
        if (empty($contract)) {
            //标记通知已读
            Message::setRead(Message::CONTRACT_TYPE, $id);
            $this->error('合同不存在');
        }
        $contract = $contract->toArray();
        $contract = ContractOther::getOther($contract);
        $receivablesMoney = Receivables::where(['contract_id' => $contract['id'], 'check_status' => 2])->sum('money');
        //回款金额
        $contract['receivables_money'] = $receivablesMoney;
        $contract['ratios'] = json_decode($contract['ratios'],true);
        if($contract['ratios']){
            foreach ($contract['ratios'] as $k => $v) {
                $v['staff'] = Staff::where(['id' => $v['staff_id']])->field('id,name,img,post')->find()->toArray();
                $v['money'] = $contract['money'] * ($v['ratio'] / 100);
                $contract['ratios'][$k] = $v;
            }
        }
        if (empty($contract['receivables'])) {
            $contract['receivables'] = [
                'repayment_money' => 0,
                'be_money' => $contract['money'],
                'ratio' => 0
            ];
        } else {
            $be_money = $contract['money'] - $contract['receivables']['repayment_money'];
            $be_ratio = 0;
            if($contract['money'] > 0){
                $be_ratio =round($contract['receivables']['repayment_money'] / $contract['money'] * 100, 2);
            }

            $contract['receivables'] = [
                'repayment_money' => $contract['receivables']['repayment_money'],
                'be_money' => ($be_money > 0) ? $be_money : 0,
                'ratio' => $be_ratio
            ];
        }
        //产品删除不显示
        if(isset($contract['product']) && $contract['product']){
            foreach($contract['product'] as $k=>$v){
                if(!$v['name'] && !$v['num']){
                    unset($contract['product'][$k]);
                }
            }
        }
        //标记通知已读
        Message::setRead(Message::CONTRACT_TYPE, $id, $this->auth->id);

        $this->success('请求成功', $contract);
    }


    //获取附件列表
    public function getFilesList()
    {
        $id = input('contract_id');

        $files = ContractFile::where(['contract_id' => $id])->field('file_id')->with(['file'])->select();
        $this->success('请求成功', $files);
    }


    //撤回审核
    public function cancel()
    {
        $id = input('id');
        $customer = ContractModel::where(['id' => $id, 'check_status' => ['in', [0, 1]]])->find();
        if (empty($customer)) {
            $this->error('合同信息不存在');
        }
        $record = ExamineRecord::where([
            'relation_type' => ExamineRecord::CONTRACT_TYPE,
            'relation_id' => $id,
            'status' => 0
        ])->find();
        Db::startTrans();
        try {
            if ($message = Message::where(['relation_type' => 'examine', 'relation_id' => $record['id'], 'from_staff_id' => $this->auth->id])->find()) {
                Message::where(['id' => $message['id']])->update(['status' => 1, 'read_time' => time()]);
            }
            ContractModel::where(['id' => $id])->update(['check_status' => 4]);
            ExamineRecord::where([
                'relation_type' => ExamineRecord::CONTRACT_TYPE,
                'relation_id' => $id,
                'status' => 0
            ])->update(['status' => 3]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();;
            $this->error($e->getMessage());
        }


        $this->success('撤回成功');
    }


    //修改合同
    public function editContract()
    {
        $id = input('id');
        $params = $this->request->post();
        $row = ContractModel::where(['id' => $id, 'check_status' => ['in', [3, 4]]])->find();
        if (empty($row)) {
            $this->error('合同信息不存在');
        }
        // 表单验证
        if (($result = $this->qingdongValidate($params, get_class(), 'create')) !== true) {
            $this->error($result);
        }
        $result = FormField::checkFields(FormField::CONTRACT_TYPE, $params,$id);
        if ($result !== true) {
            $this->error($result);
        }
        Db::startTrans();
        try {
            $params['owner_staff_id'] = $row['owner_staff_id'];
            $result = ContractModel::updateContract($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改合同信息成功');
    }
    //获取合同编号
    public function getContractNumber()
    {
        $this->success('请求成功', ['number' => ContractModel::getNum()]);
    }

    /**
     * 获取业绩分割比例
     */
    public function getRatio()
    {
        $ratios = Ratio::where(['status' => 1])->field('name,ratio')->select();
        $ratios = collection($ratios)->toArray();
        foreach ($ratios as $k => $v) {
            $v['ratio'] = json_decode($v['ratio'], true);
            $ratios[$k] = $v;
        }
        $this->success('请求成功', $ratios);
    }
}
